package util;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 仅当请求体传输的是文本类型可以使用，二进制类型不可以使用
 * @Author: ZeYu
 * @Date: 2022/3/15 10:47
 */
public class HttpUtils {

    public static String getRequestBody(HttpServletRequest request) throws IOException {
        ServletInputStream inputStream = request.getInputStream();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        int length=0;
        byte[]bytes=new byte[1024];
        while ((length=inputStream.read(bytes))!=-1){
            outputStream.write(bytes,0,length);
        }
        String requestBody=outputStream.toString("utf-8");
        outputStream.close();
        return requestBody;
    }
    public static byte[] getRequestBodyData(HttpServletRequest request) throws IOException {
        ServletInputStream inputStream = request.getInputStream();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        int length=0;
        byte[]bytes=new byte[1024];
        while ((length=inputStream.read(bytes))!=-1){
            outputStream.write(bytes,0,length);
        }
        byte[] toByteArray = outputStream.toByteArray();
        outputStream.close();
        return toByteArray;
    }



}
